package cn.itcast.controller.cargo;

import cn.itcast.base.BaseController;
import cn.itcast.domain.Role;
import cn.itcast.domain.User;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.fangkuai.Client;
import cn.itcast.service.ContractService;
import cn.itcast.service.role.RoleService;
import cn.itcast.service.user.UserService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.utils.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;
   @Autowired
    private RoleService roleService;
   @Autowired
    private UserService userService;

    @RequestMapping(name = "pageHelper插件分页查询合同",value = "/list")
    public String findAll(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        ContractExample contractExample = new ContractExample();
        //设置查询顺序
        contractExample.setOrderByClause("create_time desc");

        List<Role> userRole = roleService.findUserRole(user.getId());
        int flag=0;//普通用户
        for (Role role : userRole) {
            boolean boo = role.getName().equals("审单人");
            if(boo){
                flag=1;
            }
        }

        ContractExample.Criteria criteria = contractExample.createCriteria();
        criteria.andCompanyIdEqualTo(company_id);
        // 细颗粒度的数据控制
        if(user.getDegree()==4){
            criteria.andCreateByEqualTo(user.getId()); //根据登录用户
        }else if(user.getDegree()==3){
            criteria.andCreateDeptEqualTo(user.getDeptId()); //根据登录用户的部门
        }

        if(flag==0){    //普通用户看不到待审核的合同
            criteria.andStateNotEqualTo(3);
        }else {
            criteria.andCheckByEqualTo(user.getUserName());
        }
        PageInfo pb = contractService.findAll(contractExample,pageNum, pageSize);
        request.setAttribute("pb",pb);
        return "cargo/contract/contract-list";
    }

    @RequestMapping(name = "新增合同页面",value = "/toAdd")
    public String toAdd(){
        Role role = roleService.findId("审单人");
        List<User> sduser = userService.findByrole(role.getId());
        request.setAttribute("sdusers",sduser);
        return "cargo/contract/contract-add";
    }


    @RequestMapping(name = "新增/修改合同页面",value = "/edit")
    public String edit(Contract contract){
        System.out.println(contract.toString());
        contract.setCompanyId(company_id);
        contract.setCompanyName(company_name);
        if(UtilFuns.isEmpty(contract.getId())){
            //新增
                // 为了后期能做细颗粒度的数据控制
                            // 创建部门  创建人
            System.out.println(contract);
            contract.setCreateDept(user.getDeptId());
            contract.setCreateBy(user.getId());
            contractService.save(contract);
        }else {
            //修改
            contractService.update(contract);
        }

        return "redirect:/cargo/contract/list.do";
    }



    @RequestMapping(name = "合同修改页面回显",value = "/toUpdate")
    public String toUpdate(String id){

        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-update";
    }

    @RequestMapping(name = "调用游戏",value = "/toplay")
    public void toplay(String id){
        new Client();
    }


    @RequestMapping(name = "合同的删除",value = "/delete")
    public String delete(String id){

        contractService.delete(id);

        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(name = "合同的查看",value = "/toView")
    public String toView(String id){

        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);

        return "cargo/contract/contract-view";
    }

    @RequestMapping(name = "合同的状态提交",value = "/submit")
    public String submit(String id){

       //根据id查询合同
        Contract contract = contractService.findById(id);
        //判断合同的状态
        if(contract.getState()==0){ //草稿
            contract.setState(3);  //提交给审核人
            //修改数据库
            contractService.update(contract);
        }

        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(name = "合同的状态提交",value = "/submit1")
    public String submit1(String id){

        //根据id查询合同
        Contract contract = contractService.findById(id);
        //判断合同的状态
        if(contract.getState()==3){ //待审核
            if(user.getUserName().equals(contract.getCheckBy())){
                contract.setState(1);  //已提交
                //修改数据库
                contractService.update(contract);
            }
        }
        return "redirect:/cargo/contract/list.do";
    }



    @RequestMapping(name = "合同的状态取消",value = "/cancel")
    public String cancel(String id){

        //根据id查询合同
        Contract contract = contractService.findById(id);
        //判断合同的状态
        if(contract.getState()==1){ //已上报
            contract.setState(0);  //草稿
            //修改数据库
            contractService.update(contract);
        }

        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(name = "到出货表页面",value = "/print")
    public String print(){

        //到出货表页面
        return "cargo/print/contract-print";
    }



    @RequestMapping(name = "到出货表页面（excel模板方式--掌握）",value = "/printExcel2")
    public void printExcel2(String inputDate) throws IOException {
        //1 根据船期获取到excel需要的数据
        List<ContractProductVo> list=contractService.findExcelData(inputDate,company_id);
        //2 将数据填充到准备好的模板中
        ServletContext servletContext = session.getServletContext();
        String path = servletContext.getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        System.out.println(path);
        //读取指定路径的excel工作薄
        Workbook wb=new XSSFWorkbook(path);
        Sheet st = wb.getSheetAt(0);

        int rowIndex=0;
        Row row;
        Cell cell;
        //第一行
        row = st.getRow(rowIndex++);
        cell=row.getCell(1); //获取第一个单元格
        inputDate=inputDate.replaceAll("-0","-").replaceAll("-","年");
        cell.setCellValue(inputDate+"月份出货表"); //修改内容
        //第二行 跳过
        rowIndex++;  //2

        //第三行
        row = st.getRow(rowIndex);
        CellStyle[] cellStyles=new CellStyle[9];
        for(int i=1;i<cellStyles.length;i++){
            // 获取每个单元格的样式
            cell = row.getCell(i);
            cellStyles[i]=cell.getCellStyle();
        }
        //填充数据
        if(list.size()>0){
            //循环一个vo 就是一行8列
            for (ContractProductVo vo : list) {

                //获取行
                row=st.createRow(rowIndex++);
                //设置每行单元格
                cell=row.createCell(1);
                //给单元格内容
                cell.setCellValue(vo.getCustomName());
                //给单元格样式
                cell.setCellStyle(cellStyles[1]);

                //设置每行单元格
                cell=row.createCell(2);
                //给单元格内容
                cell.setCellValue(vo.getContractNo());
                //给单元格样式
                cell.setCellStyle(cellStyles[2]);

                //设置每行单元格
                cell=row.createCell(3);
                //给单元格内容
                cell.setCellValue(vo.getProductNo());
                //给单元格样式
                cell.setCellStyle(cellStyles[3]);

                //设置每行单元格
                cell=row.createCell(4);
                //给单元格内容
                cell.setCellValue(vo.getCnumber());
                //给单元格样式
                cell.setCellStyle(cellStyles[4]);

                //设置每行单元格
                cell=row.createCell(5);
                //给单元格内容
                cell.setCellValue(vo.getFactoryName());
                //给单元格样式
                cell.setCellStyle(cellStyles[5]);

                //设置每行单元格
                cell=row.createCell(6);
                //给单元格内容
                cell.setCellValue(vo.getDeliveryPeriod());
                //给单元格样式
                cell.setCellStyle(cellStyles[6]);

                //设置每行单元格
                cell=row.createCell(7);
                //给单元格内容
                cell.setCellValue(vo.getShipTime());
                //给单元格样式
                cell.setCellStyle(cellStyles[7]);

                //设置每行单元格
                cell=row.createCell(8);
                //给单元格内容
                cell.setCellValue(vo.getTradeTerms());
                //给单元格样式
                cell.setCellStyle(cellStyles[8]);
                }

        }

        //3 下载准备好的出货表
        //byteArrayOutputStream
        //response
        //文件名
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DownloadUtil downloadUtil = new DownloadUtil();
        wb.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表(使用excel模板).xlsx");


    }





    @RequestMapping(name = "到出货表页面2",value = "/printExcel")
    public void printExcel(String inputDate) throws IOException {

        //1 根据船期获取到excel需要的数据
        List<ContractProductVo> list=contractService.findExcelData(inputDate,company_id);
        System.out.println(list.size());  //163
        //2 将数据写入到excel表中
            // 1 创建工作薄和工作页以及设置列宽
        Workbook wb=new SXSSFWorkbook();
        Sheet st = wb.createSheet();
        st.setColumnWidth(1,26*256);
        st.setColumnWidth(2,12*256);
        st.setColumnWidth(3,30*256);
        st.setColumnWidth(4,12*256);
        st.setColumnWidth(5,15*256);
        st.setColumnWidth(6,10*256);
        st.setColumnWidth(7,10*256);
        st.setColumnWidth(8,8*256);

        int rowIndex=0; //行数
        Row row;  //行
        Cell cell; //单元

        // 2 设置第一行
        row = st.createRow(rowIndex++);//初始0  用完就+1
        row.setHeightInPoints(36); //行高
        cell=row.createCell(1); //创建单元格
        st.addMergedRegion(new CellRangeAddress(0,0,1,8)); //合并单元
        //inputDate==2015-01 2015-11
        inputDate=inputDate.replaceAll("-0","-").replaceAll("-","年");
        cell.setCellValue(inputDate+"月份出货表"); //设置单元格数据
        CellStyle cellStyle = bigTitle(wb);//设置第一行数据的样式
        cell.setCellStyle(cellStyle);
        // 3 设置第二行
        row = st.createRow(rowIndex++);//初始1  用完就+1
        row.setHeightInPoints(26); //行高
        String[] arr={"","客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for(int i=1;i<arr.length;i++){
            //创建第二行的单元格
            cell=row.createCell(i);
            //给创建的该单元格放入数据
            cell.setCellValue(arr[i]);
            //给单元格设置样式
            cell.setCellStyle(title(wb));
        }
        // 4 设置第三行到最后（list数据）
        if(list.size()>0){
            //循环一个vo 就是一行8列
            for (ContractProductVo vo : list) {

                for(int i=0;i<4000;i++){
                //创建行
                row=st.createRow(rowIndex++);
                //设置行高
                row.setHeightInPoints(26);
                //创建单元格
                cell=row.createCell(1);
                //给单元格内容
                cell.setCellValue(vo.getCustomName());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(2);
                //给单元格内容
                cell.setCellValue(vo.getContractNo());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(3);
                //给单元格内容
                cell.setCellValue(vo.getProductNo());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(4);
                //给单元格内容
                cell.setCellValue(vo.getCnumber());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(5);
                //给单元格内容
                cell.setCellValue(vo.getFactoryName());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(6);
                //给单元格内容
                cell.setCellValue(vo.getDeliveryPeriod());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(7);
                //给单元格内容
                cell.setCellValue(vo.getShipTime());
                //给单元格样式
                //cell.setCellStyle(text(wb));

                //创建单元格
                cell=row.createCell(8);
                //给单元格内容
                cell.setCellValue(vo.getTradeTerms());
                //给单元格样式
                //cell.setCellStyle(text(wb));
                }
            }
        }

        //3 下载准备好的出货表
                //byteArrayOutputStream
                //response
                //文件名
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DownloadUtil downloadUtil = new DownloadUtil();
        wb.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表(自己写excel).xlsx");
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }



}
